package com.holiday.eshop.module.protocol;

import android.os.Message;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author
 * @version 1.0
 * @date 2017/4/21
 */

public class BaseProtocol {
    private RetrofitService retrofitService;
    
    public BaseProtocol() {
        retrofitService = ProtocolManager.getInstance().getRetrofitService();
    }
    
    public RetrofitService getRetrofitService() {
        return retrofitService;
    }
    
    public <T> void execute(Call<JsonObject> call, final CallBack callBack, final Class<T> clzz, final int type, final int what) {
        
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                String json = response.body().toString();
                Gson gson = new Gson();
                T bean = gson.fromJson(json.toString(), clzz);
                Message message = new Message();
                message.what = what;
                message.obj = bean;
                callBack.onSuccess(message, type);
            }
            
            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                callBack.onFail(t.getMessage());
            }
        });
    }
    
    public <T> void execute(Call<JsonObject> call, final CallBack callBack, final Class<T> clzz, int type) {
        this.execute(call, callBack, clzz, type, 0);
    }
    
    public interface CallBack {
        void onSuccess(Message message, int type);
        
        void onFail(String e);
    }
}
